package logic

import (
	"context"
	"database/sql"

	"googee/common/tool"
	"googee/service/user/rpc/internal/svc"
	"googee/service/user/rpc/types/user"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type BindPhoneLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBindPhoneLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindPhoneLogic {
	return &BindPhoneLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 绑定手机
func (l *BindPhoneLogic) BindPhone(in *user.BindPhoneRequest) (*user.BindPhoneResponse, error) {
	phone := in.GetPhone()
	if phone == "" {
		return nil, status.Error(codes.InvalidArgument, "phone can not be empty")
	}

	b := tool.VerifyMobileFormat(phone)
	if !b {
		return nil, status.Errorf(codes.InvalidArgument, "phone number %s is not a valid", phone)
	}

	userInfo, err := l.svcCtx.UserModel.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, status.Error(codes.NotFound, "id was not found")
	}
	userInfo.Phone = sql.NullString{String: in.Phone, Valid: true}
	err = l.svcCtx.UserModel.Update(l.ctx, userInfo)
	if err != nil {
		logx.Error(err)
		return nil, status.Errorf(codes.AlreadyExists, "phone number %s has been bind already", phone)
	}

	var resp = &user.BindPhoneResponse{}
	_ = copier.Copy(&resp, userInfo)
	return resp, nil
}
